/**
 * Live GPS Tracking Application
 * Configuration provider
 *
 * Copyright 2009, Ivar Clemens
 */

package nl.ivarclemens.config;

import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;
import javax.microedition.rms.RecordStoreNotOpenException;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.InvalidRecordIDException;

/**
 * Provides access to configuration options
 */
public class Config {

    RecordStore rs = null;

    public Config() {
        try {
            rs = RecordStore.openRecordStore("GPStore", true);
        } catch(RecordStoreException exeption) {
        }
    }

    private int getOptionId(String recordName)
    {
        /* Recordstore is not open, return invalid */
        if(rs == null)
            return -1;

        /* Search for record */
        ConfigFilter filter = new ConfigFilter(recordName);

        RecordEnumeration re = null;

        try {
            re = rs.enumerateRecords(filter, null, false);
        } catch(RecordStoreNotOpenException exception) {
            return -1;
        }

        /* Return invalid if the key does not exist... */
        if(re.numRecords() < 1)
            return -1;

        try {
            return re.nextRecordId();
        } catch(InvalidRecordIDException exception) {
            return -1;
        }
    }

    public String getOption(String recordName)
    {
        /* Recordstore is not open, return default */
        if(rs == null)
            return "";

        /* Get ID */
        int optionId = this.getOptionId(recordName);

        if(optionId == -1)
            return "";

        /* Retreive actual record */
        String record = "";

        try {
            record = new String(rs.getRecord(optionId));
        } catch(RecordStoreException exception) {
            return "Invalid";
        }

        int sepPosition = record.indexOf("|");

        return record.substring(sepPosition + 1);
    }

    /**
     * Sets option only in case no previous values exists.
     */
    public void setOptionDefault(String recordName, String defaultValue)
    {
        if(rs == null)
            return;

        int optionId = this.getOptionId(recordName);

        if(optionId == -1)
            this.setOption(recordName, defaultValue);
    }

    public void setOption(String recordName, String value)
    {
        if(rs == null)
            return;

        int optionId = this.getOptionId(recordName);

        String data = recordName + "|" + value;

        try {
            if(optionId == -1)
                rs.addRecord(data.getBytes(), 0, data.length());
            else
                rs.setRecord(optionId, data.getBytes(), 0, data.length());
        } catch(RecordStoreException exception) {
        }
    }
}
